package main

import (
	"encoding/binary"

	"gitee.com/gricks/sign"
)

const (
	signature_Size            = 16
	signature_OffsetUid       = 0
	signature_OffsetGid       = 4
	signature_OffsetNumber    = 8
	signature_OffsetTimestamp = 12
)

var (
	cipher *sign.Sign
)

func init() {
	var err error
	cipher, err = sign.NewSign([]byte("0123456789abcdef"))
	if err != nil {
		panic(err)
	}
}

type Signature struct {
	Gid       uint32
	Uid       uint32
	Number    uint32
	Timestamp uint32
}

func (this *Signature) Verify(Gid, Uid, Number, Timestamp uint32) bool {
	if this.Gid != Gid ||
		this.Uid != Uid ||
		this.Number != Number ||
		this.Timestamp != Timestamp {
		return false
	}
	return true
}

func Encryp(s *Signature) ([]byte, error) {
	b := make([]byte, signature_Size)
	binary.BigEndian.PutUint32(b[signature_OffsetUid:], s.Uid)
	binary.BigEndian.PutUint32(b[signature_OffsetGid:], s.Gid)
	binary.BigEndian.PutUint32(b[signature_OffsetNumber:], s.Number)
	binary.BigEndian.PutUint32(b[signature_OffsetTimestamp:], s.Timestamp)

	cb, err := cipher.Encryp(b)
	if err != nil {
		return nil, err
	}

	return cb, nil
}

func Decryp(cb []byte) (*Signature, error) {
	b, err := cipher.Decryp(cb)
	if err != nil {
		return nil, err
	}

	s := &Signature{
		Uid:       binary.BigEndian.Uint32(b[signature_OffsetUid:]),
		Gid:       binary.BigEndian.Uint32(b[signature_OffsetGid:]),
		Number:    binary.BigEndian.Uint32(b[signature_OffsetNumber:]),
		Timestamp: binary.BigEndian.Uint32(b[signature_OffsetTimestamp:]),
	}

	return s, nil
}
